package com.upb.webserver.company;

import cn.hutool.core.collection.CollectionUtil;
import com.upb.webserver.common.enums.PlatformEnum;
import com.upb.webserver.common.exception.WebServerException;
import com.upb.webserver.common.returncode.ConstantCode;
import com.upb.webserver.common.tools.JsonUtils;
import com.upb.webserver.dao.entity.TbCompanyDeveloper;
import com.upb.webserver.dao.entity.TbCompanyDeveloperExample;
import com.upb.webserver.dao.mapper.TbCompanyDeveloperMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CompanyDeveloperManager {
    @Autowired
    private TbCompanyDeveloperMapper tbCompanyDeveloperMapper;


    /**
     * @param platform
     * @param accountId
     * @return
     */
    public List<TbCompanyDeveloper> listByPlatformAndAccountId(byte platform, int accountId) {
        TbCompanyDeveloperExample example = new TbCompanyDeveloperExample();
        TbCompanyDeveloperExample.Criteria criteria = example.createCriteria();
        criteria.andCreateFromPlatformEqualTo(platform);
        criteria.andCreateByEqualTo(accountId);

        List<TbCompanyDeveloper> companyDeveloperList = tbCompanyDeveloperMapper.selectByExample(example);
        log.info("companyDeveloperList:{}", JsonUtils.objToString(companyDeveloperList));
        return companyDeveloperList;
    }

    /**
     * @param platform
     * @param accountId
     * @return
     */
    public List<Integer> listCompanyIdByPlatformAndAccountId(byte platform, int accountId) {
        List<TbCompanyDeveloper> companyDeveloperList = listByPlatformAndAccountId(platform, accountId);
        return CollectionUtil.emptyIfNull(companyDeveloperList).stream().map(c -> c.getCompanyId()).collect(Collectors.toList());
    }


    /**
     * @param platform
     * @param accountId
     * @return
     */
    public List<Integer> listDeveloperIdByPlatformAndAccountId(byte platform, int accountId) {
        List<TbCompanyDeveloper> companyDeveloperList = listByPlatformAndAccountId(platform, accountId);
        return CollectionUtil.emptyIfNull(companyDeveloperList).stream().map(c -> c.getDeveloperId()).collect(Collectors.toList());
    }


    /**
     * @param companyId
     * @param platform
     * @param managerAccountId
     */
    public void requireCompanyFoundByPlatformAndManager(int companyId, byte platform, int managerAccountId) {
        if (PlatformEnum.DEV_OPS.getId() == platform)
            return;

        List<Integer> companyIdList = listCompanyIdByPlatformAndAccountId(platform, managerAccountId);
        log.info("companyIdList:{}", JsonUtils.objToString(companyIdList));
        if (CollectionUtil.emptyIfNull(companyIdList).contains(companyId))
            return;

        throw new WebServerException(ConstantCode.CAN_NOT_MODIFY_DATA_OF_COMPANY);
    }
}
